export default hook => {
	const { $ref, $watch, $reactive, $watchEffect } = hook.$m;
	return {
		isJiess: true,
		name: 'JiessDynamic',
		props() {
			return {
				ComPlus: {
					type: 'object',
					required: true
				},
				ComMinus: {
					type: 'object',
					required: true
				},
				limit: {
					type: 'number',
					default: Infinity
				},
				items: {
					type: 'array',
					required: true
				},
				initData: {
					type: 'function'
				},
				onChange: {
					type: 'function'
				},
				itemStyle: {
					type: 'object',
					default: {
						display: 'flex',
						alignItems: 'center',
						margin: '12px 12px 12px 0'
					}
				}
			}
		},
		data() {
			return {
				actions: [],
				childs: null,
				needInitial: true
			}
		},
		// items为Jiess响应式数据
		setup({ ComPlus, ComMinus, items, limit, initData, itemStyle, onChange }) {
			let arr = null;
			// ===================================
			arr = items.value.length ? [...items.value] : [initData()];
			this.childs = $ref(arr, 2);
			// -----------------------------------
			$watchEffect(() => {
				const v = items.value;
				this.needInitial && this.setValue(v);
			});
			// ===================================
			this.add({
				class: 'jiess-dynamic',
				children: {
					$proxy: this.childs,
					done: arr => {
						const arrs = this.actions.map(dd => dd.getFieldsValue());
						if (typeof onChange === 'function') onChange(arr);
						this.actions.length = 0;
						return arr.map((data, key) => {
							const values = arrs.length ? arrs[key] : data;
							return {
								style: itemStyle,
								children: [{
										$slot: 'default',
										$slotData: { values }
									},
									(() => {
										if (key === 0) {
											if (arr.length < limit) {
												return { is: ComPlus, onClick: () => this.itemAdd() };
											}
										} else {
											return { is: ComMinus, onClick: () => this.itemDel(data, key) };
										};
									})()
								]
							};
						});
					}
				}
			})
		},
		methods: {
			itemAdd() {
				this.childs.value = [...this.childs.value, this.$props.initData()];
			},
			itemDel(data, key) {
				this.actions.splice(key, 1);
				this.childs.value = this.childs.value.filter(dd => dd !== data);
			},
			setValue(value) {
				if (Array.isArray(value) && value.length > 1) {
					this.needInitial = false;
					this.childs.value = [...value];
				}
			}
		}
	}
}